import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { BusinessException } from '../../types/exception/business.exception';
import { ERR_MSG } from '../../types/errcode';

//  跳过路径
const skipPaths = ['/push-message/message-skip', 'com-minio/download'];

@Injectable()
export class ResponseInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<object> {
    const request = context.switchToHttp().getRequest();

    if (skipPaths.some((path) => request.url.includes(path))) {
      return next.handle();
    }
    return next.handle().pipe(
      map((res) => {
        if (Object.prototype.toString.call(res) !== '[object Object]') {
          throw new BusinessException(ERR_MSG.CUSTOM, '数据返回格式不正确');
        }
        return {
          success: true,
          code: '00000',
          data: res,
          msg: '请求成功',
          timestamp: Date.now(),
        };
      }),
    );
  }
}
